// PWM模块
module PWM #
(
	parameter	WIDTH = 1			// 产生PWM信号位数
)
(
    input                           clk, 			// 时钟频率
    input                           rst_n, 		// 复位信号，低电平有效
    output [WIDTH - 1 : 0]          dout 			// 分频后输出信号
);

localparam		PWM_MODE_UP		= 1'b0;
localparam		PWM_MODE_DOWN	= 1'b1;

wire				delay_1us;
wire				delay_1ms;
wire				delay_1s;

wire [9:0]		pulse_cnt;
wire [9:0]		display_cnt;

reg				pwm_mode;
reg				pwm_on;

always @ (posedge clk or negedge rst_n) begin
	if (!rst_n) pwm_mode <= 1'b0;
	else if (delay_1s) pwm_mode <= ~pwm_mode;
	else pwm_mode <= pwm_mode;
end

always @ (posedge clk or negedge rst_n) begin
	if (!rst_n) pwm_on <= 1'b0;
	else begin
		case (pwm_mode)
			PWM_MODE_UP		: pwm_on <= (pulse_cnt < display_cnt) ? 1'b1 : 1'b0;
			PWM_MODE_DOWN	: pwm_on <= (pulse_cnt < display_cnt) ? 1'b0 : 1'b1;
		endcase
	end
end

assign dout = {WIDTH{pwm_on}};

freq_div_in_clk #(
	.DIV_COEF (50)
)
freq_div_us (
	.clk				(clk),
	.rst_n			(rst_n),
	.out_p			(delay_1us)
);

freq_div_in_pul #(
	.DIV_COEF (1000)
)
freq_div_ms (
	.clk				(clk),
	.rst_n			(rst_n),
	.in_p				(delay_1us),
	.out_p			(delay_1ms),
	.div_cnt			(pulse_cnt)
);

freq_div_in_pul #(
	.DIV_COEF (1000)
)
freq_div_s (
	.clk				(clk),
	.rst_n			(rst_n),
	.in_p				(delay_1ms),
	.out_p			(delay_1s),
	.div_cnt			(display_cnt)
);

endmodule
